﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KnowledgeCommunity.Web.Models;
using KnowledgeCommunity.Model;
using KnowledgeCommunity.Service;

namespace KnowledgeCommunity.Web.DbHelper
{
    public class CatalogHelper
    {
        CKCDB mydb = new CKCDB();
        /// <summary>
        /// FindById(int id)
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public Catalog FindById(int id)
        {
            var app = mydb.Catalogs.Find(id);
            return app;
        }
        /// <summary>
        ///  FindByBelongTo()
        /// </summary>
        /// <param name="belongto">/所属表单：a-Documents;b-Knowledge;c-Commodity;</param>
        /// <returns></returns>
        public IEnumerable<Catalog> FindByBelongTo(string belongto) 
        {
            var app = from c in mydb.Catalogs
                      where c.BelongTo == belongto
                      orderby c.Title ascending
                      select c;
            return app;
        }

        /// <summary>
        /// SearchByUserName
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns></returns>
        public IEnumerable<Catalog> SearchByUserName(string username)
        {
            IEnumerable<Catalog> apps = null;
            apps = from n in mydb.Catalogs
                   where n.UserName==username
                   orderby n.CatalogNo descending
                   select n;
            return apps;
        }

        /// <summary>
        /// return 0-Fail; 1-Success
        /// </summary>
        /// <param name="model">Catalog</param>
        /// <returns></returns>
        public bool Create(Catalog model)
        {
            try
            {
                mydb.Catalogs.Add(model);
                mydb.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                string message = "Create in table<Catalogs>" + ex.ToString();
                WriteLog.WriteSysLog(message);
                return false;
            }
        }

        /// <summary>
        /// return 0-Fail; 1-Success
        /// </summary>
        /// <param name="model">Catalog</param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            var model = FindById(id);
            try
            {
                mydb.Catalogs.Remove(model);
                mydb.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                string message = "Delete in table<Catalogs>" + ex.ToString();
                WriteLog.WriteSysLog(message);
                return false;
            }
        }
    }
}